package net.weitalk.metrics.v2;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Aggregator {
    public static RequestStat aggregate(List<RequestInfo> requestInfos, long durationInMillis) {
        double maxResponseTime = Double.MIN_VALUE;
        double minResponseTime = Double.MAX_VALUE;
        double avgResponseTime = -1;
        double p999ResponseTime = -1;
        double p99ResponseTime = -1;
        double sumResponseTime = 0;
        long count = 0;
        for (RequestInfo requestInfo : requestInfos) {
            ++count;
            double responseTime = requestInfo.getResponseTime();
            if (maxResponseTime < responseTime) {
                maxResponseTime = responseTime;
            }
            if (minResponseTime > responseTime) {
                minResponseTime = responseTime;
            }
            sumResponseTime += responseTime;
        }
        if (count != 0) {
            avgResponseTime = sumResponseTime / count;
        }
        long tps = (long)(count / durationInMillis * 1000);
        Collections.sort(requestInfos, new Comparator<RequestInfo>() {

            @Override
            public int compare(RequestInfo rt1, RequestInfo rt2) {
                double diff = rt1.getResponseTime() - rt2.getResponseTime();
                if (diff < 0.0) {
                    return -1;
                } else if (diff > 0.0) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        int idx999 = (int) (count * 0.999);
        int idx99 = (int) (count * 0.99);
        if (count != 0) {
            p999ResponseTime = requestInfos.get(idx999).getResponseTime();
            p99ResponseTime = requestInfos.get(idx99).getResponseTime();
        }
        RequestStat requestStat = new RequestStat();
        requestStat.setMaxResponseTime(maxResponseTime);
        requestStat.setMinResponseTime(minResponseTime);
        requestStat.getAvgResponseTime(avgResponseTime);
        requestStat.setP999ResponseTime(p999ResponseTime);
        requestStat.setP99ResponseTime(p99ResponseTime);
        requestStat.setCount(count);
        requestStat.setTps(tps);
        return requestStat;
    }
}
